package net.osin.playscalajs.ajax

import com.thoughtworks.binding.{Binding, FutureBinding}
import org.lrng.binding.html
import org.scalajs.dom.ext.Ajax
import org.scalajs.dom.html.Div
import org.scalajs.dom.raw.FormData

import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue
import scala.scalajs.js.JSON
import scala.util.{Failure, Success}

object View {

  @html def render:Binding[Div] =
  {
    <div>
      <hr/>
      {
      val csrf = net.osin.playscalajs.ScalaJSExample.getCSRF
      val formData = new FormData()
      formData.append("username", "my name is jerry")
      formData.append("password", "are you okay")
      val result = FutureBinding(Ajax.post("/json?csrfToken="+csrf, data = JSON.stringify(JSON.parse("""{
        "name": "my name is jerry",
        "password": "are you okay"
      }""")),headers = Map("Content-Type"->"application/json;charset=UTF-8")))
      result.bind match
      {
        case None =>
          <div>you got nothing</div>
        case Some(Failure(exception)) =>
          <div>{ "i am the exception " + exception.getMessage + exception.getStackTrace }</div>
        case Some(Success(response)) =>
          val user=JSON.parse(response.responseText)
          <div>
            <p>message={user.message.toString}</p>
            <p>name={user.name.toString}</p>
            <p>password={user.password.toString}</p>
            <p>response.responseText= new text={JSON.stringify(response.responseText)}</p>
          </div>
      }
      }
      <hr/>
    </div>
  }
}
